#!/bin/bash
#### Usage: sh dbRestore.sh FILEPATH DBNAME
usage ()
{
	echo "Usage: sh $0  <mysql|mongo> <db-backup-path> [database-name]"
	echo "db-backup-path - For mysql, give dump file path. For mongo, give the path for folder that contains DB backup"
	echo "database-name - Mysql database name to which backup contents to be added. For mongo, this is optional field and require only if you need to restore a specific database"
}

db_type=$1
if [ "$db_type" = "mysql" ]
then
	if [ $# != 3 ]
	then
		usage
		exit
	fi
	
	CAT="/bin/cat"
	file=$2;
	db=$3;
	msp="msp"
	msp_report="msp_report"
	msp_mon="msp_mon"
	if [ "$db" = "msp" ] || [ "$db" = "$msp_report" ] || [ "$db" = "$msp_mon" ]; then
		SQL_FILE=$(echo "$file" | sed -e 's/[[:space:]]*//')
		fromdos $SQL_FILE
		$CAT $SQL_FILE | /usr/bin/mysql --f --user=root --password=xAVa6Aze $db
		if [ $? -ne 0 ]; then
			echo "Failed to install the db schema "
		else
			echo "Successfully restored the db schema"
		fi
	else
		echo "Invalid DB"
		exit;
	fi
elif [ "$db_type" = "mongo" ]
then
	if [ $# -lt 2 ]
	then
		usage
		exit
	fi
	BACKUP_DIR=$2;
	BACKUP_DB=$3;
	if [ ! -d "$BACKUP_DIR" ]
	then
		echo "Backup directory ${BACKUP_DIR} does not exist."
		exit 1
	fi

	if [ ! -z "$BACKUP_DB" ]
	then
		mongorestore --drop $BACKUP_DIR --db $BACKUP_DB
		if [ $? -eq 0 ]; then
			echo "Restored the mongo database ${BACKUP_DB} successfully"
		else
			echo "Failed to restore mongo database - $BACKUP_DB"
		fi
	else
		mongorestore --drop $BACKUP_DIR
		if [ $? -eq 0 ]; then
			echo "Restored the mongo database ${BACKUP_DB} successfully"
		else
			echo "Failed to restore entire mongo database"
		fi
	fi
else
	echo "Provide MySQL / MongoDB as DB type."
	usage
	exit
fi
